package com.app.backend.config.feign;

import com.fasterxml.jackson.annotation.JsonProperty;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.lang.reflect.Type;

/**
 * @author Jet Zheng
 */
@Slf4j
public class FeignObjectToUrlParamEncoder implements Encoder {

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate requestTemplate) throws EncodeException {
        try {
            FieldUtils.getAllFieldsList(object.getClass()).stream().forEach(x -> {
                try {
                    Object value = FieldUtils.readField(x, object, true);

                    if (value != null) {
                        JsonProperty jsonProperty = x.getAnnotation(JsonProperty.class);
                        if (jsonProperty == null) {
                            //URLEncoder.encode(value.toString(), StandardCharsets.UTF_8.displayName())
                            requestTemplate.query(x.getName(), value.toString());
                        } else {
                            //URLEncoder.encode(value.toString(), StandardCharsets.UTF_8.displayName())
                            requestTemplate.query(jsonProperty.value(), value.toString());
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
            requestTemplate.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        } catch (Exception e) {
            log.error("FeignFormEncoder.encode出错,错误原因:" + e);
            throw new RuntimeException("FeignFormEncoder.encode出错,错误原因:" + e);
        }
    }
}
